<template>
  <view class="receive-detail-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">收文详情</text>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 详情内容 -->
    <view class="detail-content" v-else-if="documentDetail">
      <!-- Tab 切换 -->
      <view class="tab-bar">
        <!-- <view
          class="tab-item"
          :class="{ active: activeTab === 'redHeader' }"
          @click="activeTab = 'redHeader'"
          v-if="documentDetail.documentUrl"
        >
          <text>红头文件</text>
        </view> -->
        <view
          class="tab-item"
          :class="{ active: activeTab === 'card' }"
          @click="activeTab = 'card'"
        >
          <text>收文卡片</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'flow' }"
          @click="activeTab = 'flow'"
        >
          <text>流程记录</text>
        </view>
      </view>

      <!-- 红头文件 Tab -->
      <scroll-view class="tab-content" scroll-y v-if="activeTab === 'redHeader'">
        <view class="pdf-preview">
          <view v-if="documentDetail.documentUrl" class="pdf-preview-area">
            <view class="preview-tips">
              <text class="tips-icon">📄</text>
              <text class="tips-text">点击下方按钮预览红头文件</text>
            </view>
            <view class="preview-actions">
              <view class="preview-btn" @click="previewRedHeader">
                <u-icon name="eye" color="#ffffff" size="18"></u-icon>
                <text class="btn-text">预览文件</text>
              </view>
            </view>
          </view>
          <view v-else class="no-file">
            <text class="no-file-icon">📄</text>
            <text class="no-file-text">暂无红头文件</text>
          </view>
        </view>
      </scroll-view>

      <!-- 收文卡片 Tab -->
      <scroll-view class="tab-content" scroll-y v-if="activeTab === 'card'">
        <view class="piyue-card">
          <view class="card-title">阳泉市卫生健康委员会文件批阅卡</view>

          <!-- 基本信息表格 -->
          <view class="info-table">
            <!-- 第一行：5个字段 -->
            <view class="table-row">
              <view class="table-cell">
                <text class="cell-label">来文单位</text>
                <text class="cell-value">{{ documentDetail.sourceCompanyName || '-' }}</text>
              </view>
              <view class="table-cell">
                <text class="cell-label">文件字号</text>
                <text class="cell-value">{{ documentDetail.receiveDocumentSymbol || '-' }}</text>
              </view>
            </view>
            <view class="table-row">
              <view class="table-cell">
                <text class="cell-label">收文时间</text>
                <text class="cell-value">{{ formatDate(documentDetail.receiveDocumentTime) }}</text>
              </view>
              <view class="table-cell">
                <text class="cell-label">收文编号</text>
                <text class="cell-value">{{ documentDetail.receiveDocumentNumber || '-' }}</text>
              </view>
            </view>
            <!-- <view class="table-row single-cell">
              <view class="table-cell full-width">
                <text class="cell-label">收文编号</text>
                <text class="cell-value">{{ documentDetail.receiveDocumentNumber || '-' }}</text>
              </view>
            </view> -->

            <!-- 文件标题 -->
            <view class="table-row single-cell">
              <view class="table-cell full-width">
                <text class="cell-label">文件标题</text>
                <text class="cell-value title">{{
                  documentDetail.sourceDocumentTitle || documentDetail.title || '-'
                }}</text>
              </view>
            </view>

            <!-- 领导批示 -->
            <view class="table-row single-cell">
              <view class="table-cell full-width column">
                <text class="cell-label">领导批示</text>
                <view class="multi-comments">
                  <view class="comment-item" v-for="(leader, index) in leaderComments" :key="index">
                    <text v-if="!leader.signature" class="comment-content">{{
                      leader.content
                    }}</text>
                    <image
                      v-if="leader.signature"
                      :src="leader.signature"
                      mode="widthFix"
                      class="signature-img-sm"
                      @click.stop="previewImage(leader.signature)"
                    />
                    <text class="comment-meta">{{ leader.userName }} {{ leader.date }}</text>
                  </view>
                  <view v-if="leaderComments.length === 0" class="empty-comment">
                    <text>暂无批示</text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 拟办意见 -->
            <view class="table-row single-cell">
              <view class="table-cell full-width column">
                <text class="cell-label">拟办意见</text>
                <view class="single-comment">
                  <text v-if="!dealView.signature" class="comment-content">{{
                    dealView.content || '-'
                  }}</text>
                  <image
                    v-if="dealView.signature"
                    :src="dealView.signature"
                    mode="widthFix"
                    class="signature-img-sm"
                    @click.stop="previewImage(dealView.signature)"
                  />
                  <text class="comment-meta" v-if="dealView.userName"
                    >{{ dealView.userName }} {{ dealView.date }}</text
                  >
                </view>
              </view>
            </view>

            <!-- 办理情况 -->
            <view class="table-row single-cell">
              <view class="table-cell full-width column">
                <text class="cell-label">办理情况</text>
                <view class="multi-comments">
                  <view
                    class="comment-item"
                    v-for="(situation, index) in dealSituations"
                    :key="index"
                  >
                    <text v-if="!situation.signature" class="comment-content">{{
                      situation.content
                    }}</text>
                    <image
                      v-if="situation.signature"
                      :src="situation.signature"
                      mode="widthFix"
                      class="signature-img-sm"
                      @click.stop="previewImage(situation.signature)"
                    />
                    <text class="comment-meta">{{ situation.userName }} {{ situation.date }}</text>
                  </view>
                  <view v-if="dealSituations.length === 0" class="empty-comment">
                    <text>暂无办理记录</text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 附件列表 -->
            <view class="table-row single-cell">
              <view class="table-cell full-width column">
                <text class="cell-label">附件</text>
                <view class="attachment-area">
                  <view v-if="documentDetail.documentUrl" class="red-preview">
                    <view class="file-info">
                      <text class="file-icon">📑</text>
                      <view class="file-details">
                        <text class="tips-text">红头文件</text>
                        <text class="file-badge">正式文件</text>
                      </view>
                    </view>
                    <view class="preview-actions">
                      <view class="preview-btn" @click="previewRedHeader">
                        <text class="btn-text">预览</text>
                      </view>
                    </view>
                  </view>
                  <view
                    class="attachment-item"
                    v-for="(file, index) in attachmentList"
                    :key="index"
                  >
                    <view class="file-info">
                      <text class="file-icon">📄</text>
                      <view class="file-details">
                        <text class="file-name">{{
                          showFileName(file.fileName || file.originalName)
                        }}</text>
                        <text class="file-size">{{ formatFileSize(file.fileSize) }}</text>
                      </view>
                    </view>
                    <view class="file-actions">
                      <text class="file-btn preview" @click.stop="previewFile(file)">预览</text>
                    </view>
                  </view>
                  <!-- <view v-if="attachmentList.length === 0" class="empty-comment">
                    <text>暂无附件</text>
                  </view> -->
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 流程记录 Tab -->
      <scroll-view class="tab-content" scroll-y v-if="activeTab === 'flow'">
        <view class="flow-records">
          <view class="flow-item" v-for="(record, index) in flowRecords" :key="index">
            <view class="flow-timeline">
              <view class="timeline-dot" :class="getFlowStatusClass(record)"></view>
              <view class="timeline-line" v-if="index < flowRecords.length - 1"></view>
            </view>
            <view class="flow-content">
              <view class="flow-header">
                <text class="flow-step">{{ record.stepName || '-' }}</text>
                <view class="flow-status-badge" :class="getFlowStatusClass(record)">
                  <text>{{ getFlowStatusText(record) }}</text>
                </view>
              </view>
              <view class="flow-info">
                <view class="info-row">
                  <text class="row-label">审批人：</text>
                  <text class="row-value">{{ record.approverName || '-' }}</text>
                </view>
                <view class="info-row">
                  <text class="row-label">角色：</text>
                  <text class="row-value">{{ record.approverRole || '-' }}</text>
                </view>
                <view class="info-row" v-if="record.approvedAt">
                  <text class="row-label">审批时间：</text>
                  <text class="row-value">{{ formatDateTime(record.approvedAt) }}</text>
                </view>
                <view class="info-row" v-if="record.approvalComment">
                  <text class="row-label">审批意见：</text>
                  <!-- 判断是否为图片URL -->
                  <view v-if="isImageUrl(record.approvalComment)" class="opinion-image-container">
                    <image
                      :src="record.approvalComment"
                      mode="aspectFit"
                      class="opinion-image"
                      @click.stop="previewImage(record.approvalComment)"
                    />
                  </view>
                  <text v-else class="row-value opinion">{{ record.approvalComment }}</text>
                </view>

                <view class="info-row" v-if="record.signature">
                  <text class="row-label">手写签名：</text>
                  <view class="opinion-image-container">
                    <image
                      :src="record.signature"
                      mode="aspectFit"
                      class="opinion-image"
                      @click.stop="previewImage(record.signature)"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view class="empty-flow" v-if="flowRecords.length === 0">
            <text class="empty-icon">📋</text>
            <text class="empty-text">暂无流程记录</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions" v-if="documentDetail && source === 'todo'">
      <view class="action-btn approve" @click="handleApprove">
        <text>审批</text>
      </view>
      <view class="action-btn archive" v-if="isArchiveStep" @click="handleArchive">
        <text>归档</text>
      </view>
    </view>
  </view>

  <!-- 人员选择器 -->
  <ApproverSelector
    :visible="approverSelectorVisible"
    :approverList="availableApprovers"
    :deptManageApprovers="availableDeptManageApprovers"
    :isDeptManageTransfer="isDeptManageTransfer"
    :currentStepName="currentNowStepName"
    :currentNextStepName="currentNextStepName"
    :rejectRecords="rejectRecords"
    @update:visible="approverSelectorVisible = $event"
    @confirm="handleApproverConfirm"
    @close="handleApproverSelectorClose"
  />

  <!-- 审批对话框（多人审批） -->
  <ApprovalDialog
    :visible="approvalDialogVisible"
    :documentId="documentDetail?.id || null"
    :stepOrder="receiveStepOrder || documentDetail?.receiveStepOrder || 1"
    :currentStepName="currentNowStepName"
    :nextStepName="documentDetail?.nextStepName || ''"
    :rejectRecords="rejectRecords"
    :canReject="!currentNowStepName.includes('科室')"
    @update:visible="approvalDialogVisible = $event"
    @confirm="handleApprovalConfirm"
    @close="handleApprovalDialogClose"
  />

  <!-- 归档对话框 -->
  <ArchiveDialog
    :visible="archiveDialogVisible"
    :documentId="documentDetail?.id || null"
    @update:visible="archiveDialogVisible = $event"
    @confirm="handleArchiveConfirm"
    @close="handleArchiveDialogClose"
  />

  <!-- 图片预览弹窗 -->
  <view class="image-preview-modal" v-if="showImagePreview" @click="closeImagePreview">
    <view class="preview-content" @click.stop>
      <view class="preview-header">
        <text class="preview-title">审批意见</text>
        <view class="close-btn" @click="closeImagePreview">
          <u-icon name="close" size="32" color="#333"></u-icon>
        </view>
      </view>
      <view class="preview-body">
        <image :src="previewImageUrl" mode="aspectFit" class="preview-image" :lazy-load="false" />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getReceiveRegisterById,
  getAttachmentApi,
  getReceiveFlowRecords,
  getCurrentStepApprovalType,
  getReceiveDocumentFlowByStep,
  submitApprovers,
  submitDeptManageApprovers,
  submitCooperateDistributeFlow,
  archiveReceiveDocument,
  downloadReceiveDocument,
  type ReceiveDocumentDistributeItem,
} from '@/Api/receive'
import ApproverSelector from './components/ApproverSelector.vue'
import ApprovalDialog from './components/ApprovalDialog.vue'
import ArchiveDialog from './components/ArchiveDialog.vue'

// 页面参数
const pageParams = ref<any>({})
const documentId = ref<number>(0)
const source = ref<string>('todo')
const receiveStepName = ref<string>('')
const receiveStepOrder = ref<number>(NaN)

// 当前激活的Tab
const activeTab = ref<'redHeader' | 'card' | 'flow'>('card')

// 加载状态
const loading = ref(false)

// 文档详情
const documentDetail = ref<ReceiveDocumentDistributeItem | null>(null)
const currentNowStepName = ref<any>('')
const currentNextStepName = ref<any>('')

// 流程记录
const flowRecords = ref<any[]>([])

// 附件列表
const attachmentList = ref<any[]>([])

// 领导批示（多条）
const leaderComments = ref<any[]>([])

// 拟办意见（单条）
const dealView = ref<{
  userName: string
  date: string
  content: string
  signature?: string
}>({
  userName: '',
  date: '',
  content: '',
  signature: '',
})

// 办理情况（多条）
const dealSituations = ref<any[]>([])

// 人员选择器状态
const approverSelectorVisible = ref(false)
const availableApprovers = ref<any[]>([])
const availableDeptManageApprovers = ref<any[]>([])
// 是否是协作
const isDeptManageTransfer = ref(false)

// 审批对话框状态（多人审批）
const approvalDialogVisible = ref(false)
const rejectRecords = ref<any[]>([])

// 归档对话框状态
const archiveDialogVisible = ref(false)

// 图片预览状态
const showImagePreview = ref(false)
const previewImageUrl = ref('')

// 是否为归档步骤
const isArchiveStep = computed(() => {
  const stepName = documentDetail.value?.currentStepName || ''
  return (
    stepName.includes('转办') ||
    stepName.includes('转交') ||
    stepName.includes('转发') ||
    stepName.includes('归档')
  )
})

// 页面加载时获取参数
onLoad((options: any) => {
  console.log('[详情页] 接收参数:', options)
  pageParams.value = options || {}
  documentId.value = Number(options.id) || 0
  source.value = options.source || 'view' // 默认改为 'view'，只有明确从待办页面进入时才显示审批按钮
  receiveStepName.value = options.receiveStepName || ''
  receiveStepOrder.value = options.receiveStepOrder || NaN

  if (documentId.value) {
    loadData()
  }
})

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1,
    fail: () => {
      uni.reLaunch({
        url: '/pages/document/receive/todo/index',
      })
    },
  })
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true

    // 并行加载详情、附件、流程记录
    const [detailResp, attachmentResp, flowResp] = await Promise.all([
      getReceiveRegisterById(documentId.value),
      getAttachmentApi(documentId.value),
      getReceiveFlowRecords(documentId.value),
    ])

    // 处理详情数据
    if (detailResp.code === 200) {
      documentDetail.value = detailResp.data
      console.log('[详情加载成功]', documentDetail.value)

      // 默认显示收文卡片Tab（无论是否有红头文件）
      activeTab.value = 'card'
    }

    // 处理附件数据
    if (attachmentResp.code === 200) {
      attachmentList.value = attachmentResp.data?.records || attachmentResp.data || []
      console.log('[附件加载成功]', attachmentList.value.length)
      console.log('[附件数据]', JSON.stringify(attachmentList.value, null, 2))
    }

    // 处理流程记录
    if (flowResp.code === 200) {
      flowRecords.value = flowResp.data || []
      console.log('[流程记录加载成功]', flowRecords.value.length)

      // 解析流程记录，提取领导批示、拟办意见、办理情况
      parseFlowRecords(flowRecords.value)
    }
  } catch (error: any) {
    console.error('[加载详情失败]', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 解析流程记录
const parseFlowRecords = (records: any[]) => {
  // 重置数据
  leaderComments.value = []
  dealView.value = { userName: '', date: '', content: '' }
  dealSituations.value = []

  // 临时存储，用于去重
  const leaderCommentsMap = new Map<string, any>()
  const dealSituationsMap = new Map<string, any>()

  records.forEach((record) => {
    // 判断是否为拒绝状态
    const status = record.statue || record.status
    const decision = record.decision
    const isRejected = status === 'rejected' || status === 'reject' || decision === 'reject'

    // 领导批示
    if (record.stepName === '领导批示' && !isRejected && record.isRequired === 0) {
      const userName = record.approverName || '-'
      const approvedAt = record.approvedAt || ''

      // 如果该用户已有记录，比较时间，保留最新的
      const existing = leaderCommentsMap.get(userName)
      if (!existing || (approvedAt && existing.approvedAt < approvedAt)) {
        leaderCommentsMap.set(userName, {
          userName,
          date: formatDateTime(approvedAt),
          content: record.approvalComment || '-',
          signature: record.signature,
          approvedAt, // 保存原始时间用于比较
        })
      }
    }
    // 拟办意见（办公室主任审核）
    else if (record.stepName === '办公室主任审核' && !isRejected && record.isRequired === 0) {
      dealView.value = {
        userName: record.approverName || '-',
        date: formatDateTime(record.approvedAt),
        content: record.approvalComment || '-',
        signature: record.signature, // 新增签名
      }
    }
    // 办理情况（科室相关步骤）- 过滤拒绝类型
    else if (
      record.stepName &&
      record.stepName.includes('科室') &&
      !isRejected &&
      record.isRequired === 0
    ) {
      const userName = record.approverName || '-'
      const approvedAt = record.approvedAt || ''

      // 如果该用户已有记录，比较时间，保留最新的
      const existing = dealSituationsMap.get(userName)
      if (!existing || (approvedAt && existing.approvedAt < approvedAt)) {
        dealSituationsMap.set(userName, {
          userName,
          date: formatDateTime(approvedAt),
          content: record.approvalComment || '-',
          signature: record.signature,
          approvedAt, // 保存原始时间用于比较
        })
      }
    }
  })

  // 将 Map 转换为数组，并移除临时字段
  leaderComments.value = Array.from(leaderCommentsMap.values()).map((item) => {
    const { approvedAt, ...rest } = item
    return rest
  })

  dealSituations.value = Array.from(dealSituationsMap.values()).map((item) => {
    const { approvedAt, ...rest } = item
    return rest
  })

  console.log('[解析流程记录]', {
    领导批示: leaderComments.value.length,
    拟办意见: dealView.value.content ? 1 : 0,
    办理情况: dealSituations.value.length,
  })
}

// 审批按钮
const handleApprove = async () => {
  try {
    if (!documentDetail.value) return

    // 查询当前步骤的审批类型
    const response = await getCurrentStepApprovalType(
      documentDetail.value.id,
      receiveStepOrder.value || documentDetail.value.receiveStepOrder || 1,
    )

    if (response.code === 200 && response.data) {
      const approvalType = response.data.approvalType
      rejectRecords.value = response.data.rejectRecords || []
      currentNowStepName.value = response.data.stepName || ''
      currentNextStepName.value = response.data.nextStepName || ''

      console.log('[审批类型]', approvalType)
      console.log('[退回记录]', rejectRecords.value)

      if (approvalType === 'single') {
        // 单人审批：显示人员选择器
        await loadAvailableApprovers(
          documentDetail.value.id,
          receiveStepOrder.value || documentDetail.value.receiveStepOrder || 1,
        )
        approverSelectorVisible.value = true
      } else {
        // 多人审批：显示同意/拒绝对话框
        approvalDialogVisible.value = true
      }
    } else {
      throw new Error(response.message || '获取审批类型失败')
    }
  } catch (error: any) {
    console.error('[审批失败]', error)
    uni.showToast({
      title: error.message || '审批失败',
      icon: 'none',
    })
  }
}

// 加载可选审批人员（单人审批时用）
const loadAvailableApprovers = async (documentId: number, stepOrder: number) => {
  try {
    const response = await getReceiveDocumentFlowByStep(documentId, stepOrder)

    if (response.code === 200 && response.data) {
      const approvers = response.data.approvers || []
      const deptManageApprovers = response.data.deptManageApprovers || []

      // 拿到当前步骤是否为科室办理转办为科室办理“协作”的标识
      isDeptManageTransfer.value =
        response.data.currentUserAgreedProgress?.cooperateDistributeFlowId !== null

      availableApprovers.value = approvers.map((u: any) => ({
        key: u.id,
        label: u.realName || u.nickname || u.username,
        deptName: u.deptName || '未分配部门',
        job: u.job || '领导',
      }))

      availableDeptManageApprovers.value = deptManageApprovers.map((u: any) => ({
        key: u.id,
        label: u.realName || u.nickname || u.username,
        deptName: u.deptName || '未分配部门',
        job: u.job || '领导',
      }))

      console.log('[可选审批人员]', availableApprovers.value.length)
      console.log('[其他科室可选审批人员]', availableDeptManageApprovers.value.length)
    } else {
      throw new Error(response.message || '获取审批人员失败')
    }
  } catch (error: any) {
    console.error('[加载审批人员失败]', error)
    uni.showToast({
      title: error.message || '加载审批人员失败',
      icon: 'none',
    })
  }
}

// 人员选择器确认（单人审批）
const handleApproverConfirm = async (
  approvers: Array<{ id: number; name: string }>,
  opinion: string,
  action: string,
  signature?: string, // 签名图片路径
  rejectNextStep?: string, // 退回步骤
  deptManageApprovers?: Array<{ id: number; name: string }>, // 其他科室办理人员
) => {
  try {
    if (!documentDetail.value) return

    // 协作+拒绝->调单独的接口
    if (isDeptManageTransfer.value && action === 'reject') {
      const payload = {
        bizId: documentDetail.value.id,
        approvers,
        opinion,
        signature, // 传递签名
        decision: action,
        receiveStepName:
          receiveStepName.value ||
          currentNowStepName.value ||
          documentDetail.value.currentStepName ||
          '',
        receiveStepOrder: receiveStepOrder.value || documentDetail.value.receiveStepOrder || 1,
      }
      const res = await submitCooperateDistributeFlow(payload)
      if (res.code === 200) {
        uni.showToast({
          title: '审批已拒绝',
          icon: 'success',
        })
        approverSelectorVisible.value = false

        // 延迟返回列表页，让用户看到成功提示
        setTimeout(() => {
          uni.navigateBack({
            success: () => {
              console.log('[单人审批] 成功返回列表页，onShow将自动刷新数据')
            },
          })
        }, 1500)
        return
      }
      return
    }

    const payload: any = {
      bizId: documentDetail.value.id,
      approvers,
      opinion,
      signature, // 传递签名
      decision: action,
      receiveStepName:
        receiveStepName.value ||
        currentNowStepName.value ||
        documentDetail.value.currentStepName ||
        '',
      receiveStepOrder: receiveStepOrder.value || documentDetail.value.receiveStepOrder || 1,
    }

    const payload1: any = {
      bizId: documentDetail.value.id,
      receiveStepOrder: receiveStepOrder.value || documentDetail.value.receiveStepOrder || 1,
    }

    // 如果有其他科室办理人员，添加到 payload1 调新接口
    if (deptManageApprovers && deptManageApprovers.length > 0) {
      payload1.approvers = deptManageApprovers

      submitDeptManageApprovers(payload1)
    }

    if (action === 'reject') {
      payload.receiveStepName = rejectNextStep
    }

    console.log('[单人审批提交]', payload)

    const response = await submitApprovers(payload)

    if (response.code === 200) {
      uni.showToast({
        title: '审批提交成功',
        icon: 'success',
      })
      approverSelectorVisible.value = false

      // 延迟返回列表页，让用户看到成功提示
      setTimeout(() => {
        uni.navigateBack({
          success: () => {
            console.log('[单人审批] 成功返回列表页，onShow将自动刷新数据')
          },
        })
      }, 1500)
    } else {
      throw new Error(response.message || '提交失败')
    }
  } catch (error: any) {
    console.error('[审批提交失败]', error)
    uni.showToast({
      title: error.message || '审批提交失败',
      icon: 'none',
    })
  }
}

// 人员选择器关闭
const handleApproverSelectorClose = () => {
  approverSelectorVisible.value = false
}

// 审批对话框确认（多人审批）
const handleApprovalConfirm = async (data: {
  action: 'approve' | 'reject'
  opinion: string
  signature?: string // 签名图片路径
  rejectNextStep?: string
}) => {
  try {
    if (!documentDetail.value) return

    const payload = {
      bizId: documentDetail.value.id,
      approvers: [], // 多人审批时传空数组
      opinion: data.opinion,
      signature: data.signature, // 传递签名
      decision: data.action,
      receiveStepName:
        receiveStepName.value ||
        data.rejectNextStep ||
        currentNowStepName.value ||
        documentDetail.value.currentStepName ||
        '',
      receiveStepOrder: receiveStepOrder.value || documentDetail.value.receiveStepOrder || 1,
    }

    if (data.action === 'reject') {
      payload.receiveStepName = data.rejectNextStep
    }

    console.log('[多人审批提交]', payload)

    const response = await submitApprovers(payload)

    if (response.code === 200) {
      uni.showToast({
        title: data.action === 'approve' ? '审批通过' : '已退回',
        icon: 'success',
      })
      approvalDialogVisible.value = false

      // 延迟返回列表页，让用户看到成功提示
      setTimeout(() => {
        uni.navigateBack({
          success: () => {
            console.log('[多人审批] 成功返回列表页，onShow将自动刷新数据')
          },
        })
      }, 1500)
    } else {
      throw new Error(response.message || '提交失败')
    }
  } catch (error: any) {
    console.error('[审批提交失败]', error)
    uni.showToast({
      title: error.message || '审批提交失败',
      icon: 'none',
    })
  }
}

// 审批对话框关闭
const handleApprovalDialogClose = () => {
  approvalDialogVisible.value = false
}

// 归档按钮
const handleArchive = () => {
  archiveDialogVisible.value = true
}

// 归档对话框确认
const handleArchiveConfirm = async (data: { approvalDeadline: string; opinion: string }) => {
  try {
    if (!documentDetail.value) return

    console.log('[归档提交]', data)

    const response = await archiveReceiveDocument(documentDetail.value.id, data)

    if (response.code === 200) {
      uni.showToast({
        title: '归档成功',
        icon: 'success',
      })
      archiveDialogVisible.value = false

      // 归档成功后返回列表页
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        })
      }, 1500)
    } else {
      throw new Error(response.message || '归档失败')
    }
  } catch (error: any) {
    console.error('[归档失败]', error)
    uni.showToast({
      title: error.message || '归档失败',
      icon: 'none',
    })
  }
}

// 归档对话框关闭
const handleArchiveDialogClose = () => {
  archiveDialogVisible.value = false
}

// 预览红头文件
const previewRedHeader = () => {
  if (!documentDetail.value?.documentUrl) {
    uni.showToast({
      title: '文件地址不存在',
      icon: 'none',
    })
    return
  }

  // #ifdef H5
  // H5环境直接打开链接
  if (typeof window !== 'undefined') {
    window.open(documentDetail.value.documentUrl)
  }
  // #endif

  // #ifdef APP-PLUS
  uni.showLoading({
    title: '加载中...',
  })

  uni.downloadFile({
    url: documentDetail.value.documentUrl,
    success: (res) => {
      uni.hideLoading()
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          showMenu: true,
          success: () => {
            console.log('[红头文件预览成功]')
          },
          fail: () => {
            uni.showToast({
              title: '文件格式不支持预览',
              icon: 'none',
            })
          },
        })
      }
    },
    fail: () => {
      uni.hideLoading()
      uni.showToast({
        title: '文件下载失败',
        icon: 'none',
      })
    },
  })
  // #endif
}

// 预览文件
const previewFile = (file: any) => {
  const fileUrl = file.filePath || file.documentUrl || file.fileUrl
  if (!fileUrl) {
    uni.showToast({
      title: '文件地址不存在',
      icon: 'none',
    })
    return
  }

  // #ifdef H5
  // H5环境直接打开链接
  if (typeof window !== 'undefined') {
    window.open(fileUrl)
  }
  // #endif

  // #ifdef APP-PLUS
  uni.showLoading({
    title: '加载中...',
  })

  // 在移动端打开文件预览
  uni.downloadFile({
    url: fileUrl,
    success: (res) => {
      uni.hideLoading()
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          showMenu: true,
          success: () => {},
          fail: (err) => {
            console.error('[openDocument失败]', err)
            uni.showToast({
              title: '文件格式不支持预览',
              icon: 'none',
            })
          },
        })
      } else {
        uni.showToast({
          title: `下载失败：状态码${res.statusCode}`,
          icon: 'none',
        })
      }
    },
    fail: (err) => {
      console.error('[downloadFile失败]', err)
      uni.hideLoading()
      uni.showToast({
        title: `文件下载失败：${err.errMsg || '未知错误'}`,
        icon: 'none',
        duration: 3000,
      })
    },
  })
  // #endif
}

// 显示文件名（去除时间戳前缀）
const showFileName = (filename?: string) => {
  if (!filename) return '未知文件'

  // 找到第一个下划线的位置
  const firstUnderscore = filename.indexOf('_')
  if (firstUnderscore === -1) {
    return filename
  }

  // 从第一个下划线之后开始找第二个下划线
  const secondUnderscore = filename.indexOf('_', firstUnderscore + 1)
  if (secondUnderscore === -1) {
    return filename
  }

  // 截取第二个下划线之后的部分
  return filename.substring(secondUnderscore + 1)
}

// 获取紧急程度样式类
const getUrgencyClass = (level?: string): string => {
  const levelMap: Record<string, string> = {
    low: 'low',
    normal: 'normal',
    high: 'high',
    urgent: 'urgent',
  }
  return levelMap[level || 'normal'] || 'normal'
}

// 获取紧急程度文本
const getUrgencyText = (level?: string): string => {
  const textMap: Record<string, string> = {
    low: '低',
    normal: '普通',
    high: '高',
    urgent: '紧急',
  }
  return textMap[level || 'normal'] || '普通'
}

// 获取流程状态样式类
const getFlowStatusClass = (record: any): string => {
  if (record.approvedAt) {
    // 检查多个可能的退回标识字段
    const status = record.statue || record.status
    const decision = record.decision

    // 判断是否为退回状态：status='rejected'/'reject' 或 decision='reject'
    if (status === 'rejected' || status === 'reject' || decision === 'reject') {
      return 'rejected'
    }
    return 'approved'
  }
  return 'pending'
}

// 获取流程状态文本
const getFlowStatusText = (record: any): string => {
  if (record.approvedAt) {
    // 检查多个可能的退回标识字段
    const status = record.statue || record.status
    const decision = record.decision

    // 判断是否为退回状态：status='rejected'/'reject' 或 decision='reject'
    if (status === 'rejected' || status === 'reject' || decision === 'reject') {
      return '已退回'
    }
    return '已完成'
  }
  return '待处理'
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 格式化日期时间
const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}/${month}/${day} ${hours}:${minutes}`
}

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return '-'
  if (bytes < 1024) return `${bytes}B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
}

// 判断是否为图片URL
const isImageUrl = (url?: string): boolean => {
  if (!url) return false
  // 检查是否是HTTP/HTTPS URL 或者本地临时路径
  if (
    url.startsWith('http://') ||
    url.startsWith('https://') ||
    url.startsWith('wxfile://') ||
    url.startsWith('file://') ||
    url.startsWith('blob:') ||
    url.startsWith('_doc/')
  ) {
    return true
  }
  // 检查文件扩展名
  const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp']
  const lowerUrl = url.toLowerCase()
  return imageExtensions.some((ext) => lowerUrl.includes(ext))
}

// 预览图片（使用自定义弹窗）
const previewImage = (imageUrl: string) => {
  if (!imageUrl) {
    uni.showToast({
      title: '图片地址不存在',
      icon: 'none',
    })
    return
  }

  previewImageUrl.value = imageUrl
  showImagePreview.value = true
}

// 关闭图片预览
const closeImagePreview = () => {
  showImagePreview.value = false
  previewImageUrl.value = ''
}
</script>

<style lang="scss" scoped>
.receive-detail-page {
  height: 100vh;
  background: #f8f9fa;
  // padding-bottom: 120rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  /* 顶部导航 */
  .nav-header {
    background: #1a3582;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      width: 60rpx;
    }
  }

  /* 加载状态 */
  .loading-container {
    margin-top: 100rpx;
    text-align: center;

    .loading-text {
      font-size: 28rpx;
      color: #9ca3af;
    }
  }

  /* 详情内容 */
  .detail-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  /* Tab 切换栏 */
  .tab-bar {
    display: flex;
    background: white;
    border-bottom: 1rpx solid #e5e7eb;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 28rpx 0;
      font-size: 28rpx;
      color: #6b7280;
      position: relative;

      &.active {
        color: #1a3582;
        font-weight: 600;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 80rpx;
          height: 4rpx;
          background: #1a3582;
          border-radius: 2rpx;
        }
      }
    }
  }

  /* Tab 内容 */
  .tab-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  /* 红头文件预览 */
  .pdf-preview {
    // min-height: calc(100vh - 380rpx);
    background: white;
    padding: 32rpx;
    height: 100%;

    .pdf-preview-area {
      .preview-tips {
        text-align: center;
        padding: 60rpx 0 40rpx;

        .tips-icon {
          font-size: 120rpx;
          display: block;
          margin-bottom: 24rpx;
        }

        .tips-text {
          font-size: 28rpx;
          color: #6b7280;
        }
      }

      .preview-actions {
        display: flex;
        gap: 24rpx;
        padding: 0 32rpx 40rpx;

        .preview-btn {
          flex: 1;
          background: #1890ff;
          border-radius: 12rpx;
          padding: 32rpx 24rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 12rpx;

          &.download {
            background: #10b981;
          }

          .btn-icon {
            font-size: 48rpx;
          }

          .btn-text {
            font-size: 26rpx;
            color: white;
            font-weight: 500;
          }
        }
      }

      .file-info {
        padding: 24rpx;
        background: #f9fafb;
        border-radius: 12rpx;

        .info-label {
          font-size: 24rpx;
          color: #6b7280;
          margin-bottom: 8rpx;
        }

        .info-value {
          font-size: 22rpx;
          color: #3b82f6;
          word-break: break-all;
          line-height: 1.6;
        }
      }
    }

    .no-file {
      height: calc(100vh - 420rpx);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .no-file-icon {
        font-size: 120rpx;
        margin-bottom: 24rpx;
        opacity: 0.5;
      }

      .no-file-text {
        font-size: 28rpx;
        color: #9ca3af;
      }
    }
  }

  /* 收文卡片 */
  .piyue-card {
    background: white;
    margin: 32rpx;
    padding: 40rpx 32rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);

    .card-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #1a3582;
      text-align: center;
      padding-bottom: 32rpx;
      margin-bottom: 32rpx;
      border-bottom: 3rpx solid #1a3582;
    }

    .info-table {
      border: 2rpx solid #333;
      border-radius: 8rpx;
      overflow: hidden;

      .table-row {
        display: flex;
        border-bottom: 2rpx solid #333;

        &:last-child {
          border-bottom: none;
        }

        &.single-cell {
          .table-cell {
            border-right: none;
          }
        }

        .table-cell {
          flex: 1;
          border-right: 2rpx solid #333;
          display: flex;
          flex-direction: column;

          &.full-width {
            flex: 1;
            border-right: none;
          }

          &.column {
            .cell-label {
              border-bottom: 2rpx solid #333;
            }
          }

          &:last-child {
            border-right: none;
          }

          .cell-label {
            padding: 20rpx;
            text-align: center;
            font-size: 26rpx;
            color: #374151;
            font-weight: 600;
            background: #f9fafb;
          }

          .cell-value {
            padding: 24rpx 20rpx;
            font-size: 26rpx;
            color: #1a3582;
            text-align: center;
            min-height: 80rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            &.title {
              text-align: left;
              line-height: 1.6;
              min-height: 120rpx;
            }
          }

          .urgency-badge {
            margin: 20rpx;
            padding: 10rpx 24rpx;
            border-radius: 20rpx;
            font-size: 24rpx;
            text-align: center;
            align-self: center;

            &.low {
              background: #dbeafe;
              color: #1e40af;
            }

            &.normal {
              background: #e0e7ff;
              color: #4338ca;
            }

            &.high {
              background: #fef3c7;
              color: #92400e;
            }

            &.urgent {
              background: #fee2e2;
              color: #991b1b;
            }
          }

          .multi-comments,
          .single-comment {
            padding: 24rpx;
            min-height: 120rpx;
          }

          .attachment-area {
            padding: 24rpx 20rpx;
            min-height: auto;
          }

          .comment-item,
          .single-comment {
            border-bottom: 1rpx dashed #e5e7eb;

            &:last-child {
              border-bottom: none;
            }

            .comment-content {
              display: block;
              font-size: 26rpx;
              color: #1a3582;
              line-height: 1.6;
              margin-bottom: 12rpx;
            }

            .signature-img-sm {
              // height: 60rpx;
              width: 100%;
              margin: 8rpx 0;
              display: block;
            }

            .comment-meta {
              display: block;
              font-size: 22rpx;
              color: #9ca3af;
              text-align: right;
            }
          }

          .comment-item {
            padding-bottom: 24rpx;

            &:last-child {
              border-bottom: none;
              padding-bottom: 0;
            }
          }

          .empty-comment {
            text-align: center;
            padding: 40rpx 0;
            color: #9ca3af;
            font-size: 24rpx;
          }

          .attachment-area {
            .red-preview {
              display: flex;
              flex-direction: column;
              gap: 20rpx;
              padding: 24rpx;
              background: white;
              border: 2rpx solid #e5e7eb;
              border-radius: 12rpx;
              margin-bottom: 20rpx;

              .file-info {
                display: flex;
                align-items: flex-start;
                gap: 16rpx;

                .file-icon {
                  font-size: 48rpx;
                  flex-shrink: 0;
                }

                .file-details {
                  flex: 1;
                  display: flex;
                  flex-direction: column;
                  gap: 10rpx;

                  .tips-text {
                    font-size: 28rpx;
                    color: #cf1322;
                    font-weight: 600;
                    line-height: 1.5;
                  }

                  .file-badge {
                    display: inline-flex;
                    align-items: center;
                    padding: 4rpx 16rpx;
                    background: #fff;
                    border: 1rpx solid #ffa39e;
                    border-radius: 20rpx;
                    font-size: 22rpx;
                    color: #cf1322;
                    align-self: flex-start;
                  }
                }
              }

              .preview-actions {
                display: flex;
                gap: 20rpx;

                .preview-btn {
                  flex: 1;
                  padding: 20rpx 0;
                  border-radius: 12rpx;
                  font-size: 28rpx;
                  font-weight: 600;
                  text-align: center;

                  &:not(.download):not(.share) {
                    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
                    color: white;
                    box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.3);
                  }

                  &.download {
                    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
                    color: white;
                    box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);
                  }

                  &.share {
                    background: linear-gradient(135deg, #07c160 0%, #06ad56 100%);
                    color: white;
                    box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
                  }

                  &:active {
                    opacity: 0.8;
                    transform: scale(0.98);
                  }
                }
              }
            }

            .attachment-item {
              display: flex;
              flex-direction: column;
              gap: 20rpx;
              padding: 24rpx;
              background: white;
              border: 2rpx solid #e5e7eb;
              border-radius: 12rpx;
              margin-bottom: 20rpx;

              &:last-child {
                margin-bottom: 0;
              }

              .file-info {
                display: flex;
                align-items: flex-start;
                gap: 16rpx;

                .file-icon {
                  font-size: 48rpx;
                  flex-shrink: 0;
                }

                .file-details {
                  flex: 1;
                  display: flex;
                  flex-direction: column;
                  gap: 10rpx;

                  .file-name {
                    font-size: 28rpx;
                    color: #1a3582;
                    font-weight: 600;
                    line-height: 1.5;
                    word-break: break-all;
                  }

                  .file-size {
                    font-size: 24rpx;
                    color: #6b7280;
                  }
                }
              }

              .file-actions {
                display: flex;
                gap: 20rpx;

                .file-btn {
                  flex: 1;
                  padding: 20rpx 0;
                  border-radius: 12rpx;
                  font-size: 28rpx;
                  font-weight: 600;
                  text-align: center;

                  &.preview {
                    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
                    color: white;
                    box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.3);
                  }

                  &.download {
                    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
                    color: white;
                    box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);
                  }

                  &.share {
                    background: linear-gradient(135deg, #07c160 0%, #06ad56 100%);
                    color: white;
                    box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
                  }

                  &:active {
                    opacity: 0.8;
                    transform: scale(0.98);
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  /* 流程记录 */
  .flow-records {
    padding: 32rpx;

    .flow-item {
      display: flex;
      gap: 24rpx;
      margin-bottom: 32rpx;

      .flow-timeline {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 48rpx;
        flex-shrink: 0;

        .timeline-dot {
          width: 24rpx;
          height: 24rpx;
          border-radius: 50%;
          border: 4rpx solid;
          background: white;

          &.approved {
            border-color: #10b981;
            background: #10b981;
          }

          &.rejected {
            border-color: #ef4444;
            background: #ef4444;
          }

          &.pending {
            border-color: #9ca3af;
            background: white;
          }
        }

        .timeline-line {
          flex: 1;
          width: 2rpx;
          min-height: 120rpx;
          background: #e5e7eb;
        }
      }

      .flow-content {
        flex: 1;
        background: white;
        border-radius: 12rpx;
        padding: 20rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

        .flow-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16rpx;

          .flow-step {
            font-size: 28rpx;
            font-weight: 600;
            color: #1a3582;
          }

          .flow-status-badge {
            padding: 6rpx 16rpx;
            border-radius: 12rpx;
            font-size: 22rpx;

            &.approved {
              background: #d1fae5;
              color: #065f46;
            }

            &.rejected {
              background: #fee2e2;
              color: #991b1b;
            }

            &.pending {
              background: #f3f4f6;
              color: #6b7280;
            }
          }
        }

        .flow-info {
          .info-row {
            display: flex;
            margin-bottom: 12rpx;
            line-height: 1.6;

            &:last-child {
              margin-bottom: 0;
            }

            .row-label {
              font-size: 24rpx;
              color: #6b7280;
              flex-shrink: 0;
              width: 140rpx;
            }

            .row-value {
              flex: 1;
              font-size: 24rpx;
              color: #374151;

              &.opinion {
                color: #1a3582;
                font-weight: 500;
              }
            }

            .opinion-image-container {
              flex: 1;
              display: flex;
              align-items: center;

              .opinion-image {
                max-width: 200rpx;
                max-height: 120rpx;
                border-radius: 8rpx;
                border: 1rpx solid #e5e7eb;
                cursor: pointer;
              }
            }
          }
        }
      }
    }

    .empty-flow {
      text-align: center;
      padding: 120rpx 0;

      .empty-icon {
        font-size: 120rpx;
        display: block;
        margin-bottom: 24rpx;
        opacity: 0.5;
      }

      .empty-text {
        font-size: 28rpx;
        color: #9ca3af;
      }
    }
  }

  /* 底部操作按钮 */
  .bottom-actions {
    // position: fixed;
    // bottom: 0;
    // left: 0;
    // right: 0;
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #e5e7eb;
    display: flex;
    gap: 24rpx;
    z-index: 99;

    .action-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      font-weight: 500;

      &.approve {
        background: #1a3582;
        color: white;
      }

      &.archive {
        background: #f59e0b;
        color: white;
      }
    }
  }
}

/* 图片预览弹窗 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;

  .preview-content {
    width: 90%;
    height: 60%;
    display: flex;
    flex-direction: column;
    background: #ffffff;
    /* 白色背景，确保能看到签名 */
    border-radius: 16rpx;
    overflow: hidden;

    .preview-header {
      position: relative;
      padding: 20rpx 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      background: #f8f9fa;
      border-bottom: 1rpx solid #e5e7eb;

      .preview-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .close-btn {
        position: absolute;
        right: 32rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .preview-body {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20rpx;
      overflow: hidden;

      .preview-image {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
